<?
require_once("conn.php");
	$sql = "select id from pch_order ORDER by id DESC limit 0,1";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	$order_id = $row["id"];

	$sql = "select id from pch_sendisland ORDER by id DESC limit 0,1";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	$send_id = $row["id"];

	$sql = "select * FROM pch_order_detail as tbA where order_id='".$order_id."' AND NOT EXISTS (select * FROM pch_sendisland_detail as tbB WHERE send_id='".$send_id."' AND tbA.product_id=tbB.item);";
	$query = mysql_query($sql);
	$i=0;
	$insert = "";
	$update = "";
	while($row = mysql_fetch_array($query)){
		$sqlx = "SELECT * FROM pch_unfinished WHERE item='".$row["product_id"]."';";
		$qry = mysql_query($sqlx);
		if(mysql_num_rows($qry) > 0){
			while($xrow = mysql_fetch_array($qry)){
				if($xrow["order_id"] != $order_id){
					$update = "UPDATE pch_unfinished SET amount = amount + ".$row["amount"]." WHERE id='".$xrow["id"]."';";
					mysql_query($update);
					if(mysql_error()){
						echo mysql_error()."\n".$sql;
					}
				}
			}
		}else{
			if($i > 0){
				$insert .= ",('".$row["order_id"]."','".$row["product_id"]."','".$row["amount"]."','".$row["unit"]."','".$row["last_update"]."')";
			}else{
				$insert = "('".$row["order_id"]."','".$row["product_id"]."','".$row["amount"]."','".$row["unit"]."','".$row["last_update"]."')";;
			}
		}
		$i++;
	}

	if($insert != ""){
		$inssql = "INSERT INTO pch_unfinished(order_id,item,amount,unit,orderTime) VALUES";
		$inssql .= $insert.";";
		mysql_query($inssql);
		if(mysql_error()){
			echo mysql_error()."\n".$inssql;
		}
	}	
?>